package cn.hamster3.mc.plugin.ball.common.listener;

import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.data.BallMessage;
import cn.hamster3.mc.plugin.ball.common.event.message.MessageReceivedEvent;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import com.google.common.eventbus.EventBus;
import redis.clients.jedis.JedisPubSub;

public class BallRedisListener extends JedisPubSub {
    public static final BallRedisListener INSTANCE = new BallRedisListener();

    private BallRedisListener() {
    }

    @Override
    public void onMessage(String channel, String message) {
        if (channel.startsWith(BallAPI.getInstance().getBallConfig().getChannelPrefix())) {
            channel = channel.substring(BallAPI.getInstance().getBallConfig().getChannelPrefix().length());
        }
        BallMessage ballMessage = CoreAPI.getInstance().getGson().fromJson(message, BallMessage.class);
        BallAPI ballAPI = BallAPI.getInstance();
        EventBus eventBus = ballAPI.getEventBus();
        if (ballMessage.getReceiverType() != null && ballMessage.getReceiverType() != ballAPI.getLocalServerInfo().getType()) {
            return;
        }
        if (ballMessage.getReceiverID() != null && !ballAPI.isLocalServer(ballMessage.getReceiverID())) {
            return;
        }
        eventBus.post(new MessageReceivedEvent(channel, ballMessage));
    }

    @Override
    public void onPMessage(String pattern, String channel, String message) {
        onMessage(channel, message);
    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        BallAPI.getInstance().getLogger().info("已订阅 redis 频道 " + channel);
    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        BallAPI.getInstance().getLogger().info("已取消订阅 redis 频道 " + channel);
    }

    @Override
    public void onPSubscribe(String pattern, int subscribedChannels) {
        BallAPI.getInstance().getLogger().info("已订阅 redis 频道（正则） " + pattern);
    }

    @Override
    public void onPUnsubscribe(String pattern, int subscribedChannels) {
        BallAPI.getInstance().getLogger().info("已取消订阅 redis 频道（正则） " + pattern);
    }
}
